package com.jxud.filter;

import com.jxud.Pojo.Result;
import com.jxud.utils.DesensitizationContextHolder;
import com.jxud.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.io.IOException;

@WebFilter(urlPatterns = "/api/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求的url
        String url =  request.getRequestURI();
        log.info("请求的url:{}",url);

        // 放行登录接口和 OPTIONS 预检
        if (url.equals("/api/auth/login") || "OPTIONS".equalsIgnoreCase(request.getMethod())
                || url.equals("/api/images/upload")
                || url.equals("/api/auth/register")
                || url.equals("/api/privacy")
        ) {
            log.info("登录或预检请求，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 获取 Token 请求头
        String jwt = request.getHeader("Token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头中无 Token，返回未登录");
            response.setContentType("application/json;charset=UTF-8");
            String notLogin = JSONObject.toJSONString(Result.error("NOT LOGIN"));
            response.getWriter().write(notLogin);
            return;
        }

        //  解析JWT令牌 如果解析错误 返回错误结果 （未登录）
        try{
            JwtUtils.parseJwt(jwt);
        }catch (Exception e){
            log.warn("解析令牌失败 返回未登录令牌信息: {}", e.getMessage());
            Result error = Result.error(321,"NOT LOGIN");
            // 手动转化  对象----json
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        // 放心
        log.info("令牌合法");

        //判断是否需要脱敏
        if (shouldDisableDesensitization(request)) {
            try {
                DesensitizationContextHolder.disableDesensitization();
                filterChain.doFilter(request, response);
            } finally {
                DesensitizationContextHolder.enableDesensitization();
                DesensitizationContextHolder.clear();
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    private boolean shouldDisableDesensitization(HttpServletRequest request) {
        // 实现您的逻辑，例如检查特定路径、参数或头信息
        String path = request.getRequestURI();
        return path.contains("/api/order/desens") ||
                "true".equals(request.getHeader("X-No-Desensitization"));
    }
}
